class oss_util {
	constructor(data) {
		
		this.accessid = data.accessKeyId; //accessid, accesskey, host, stsToken, dir, signature, policyBase64, region, buckName, endpoint
		this.accesskey = data.accessKeySecret;
		this.host = data.host;
		this.stsToken = data.securityToken;
		this.dir = data.dir;
		this.signature = data.signature;
		this.policyBase64 = data.polocyBase64;
		this.region = data.region;
		this.buckName = data.buckName;
		this.endpoint = data.endpoint;
		const OSS = require('ali-oss');
		
		this.client = new OSS({
			region: this.region,
			endpoint: this.endpoint,
			bucket:this.buckName,
			accessKeyId: this.accessid,
			accessKeySecret: this.accesskey,
			stsToken: this.stsToken,
			
		})
		console.info(data)
		return this;
	}

	// function get_signature() {
	//     policyBase64 = Base64.encode(JSON.stringify(policyText))
	//     message = policyBase64
	//     var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, { asBytes: true }) ;
	//     this.signature = Crypto.util.bytesToBase64(bytes);
	// }

	 random_string(len) {
		len = len || 32;
		var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
		var maxPos = chars.length;
		var pwd = '';
		for (let i = 0; i < len; i++) {
			pwd += chars.charAt(Math.floor(Math.random() * maxPos));
		}
		return pwd;
	}

	 get_path(filename,dir) {
		return dir + this.random_string(32) + this.get_suffix(filename);
	}

	 get_suffix(filename) {
		var pos = filename.lastIndexOf('.')
		var suffix = ''
		if (pos != -1) {
			suffix = filename.substring(pos)
		}
		return suffix;
	}

	 get_upload_param(filename,dir,isRandomName,newFileNameWithOutSuffix) {
		var path = "";
		if(isRandomName == true) {
			path = this.get_path(filename);
		}else if(newFileNameWithOutSuffix !=null && newFileNameWithOutSuffix.length > 0){
			path = dir + newFileNameWithOutSuffix + this.get_suffix(filename)
		}else{
			var pos = filename.lastIndexOf('/')
			var name = ''
			if (pos != -1) {
				name = filename.substring(pos + 1)
			}
			path = this.dir + name;
		}

		var new_multipart_params = {
			'key': path,
			'policy': this.policyBase64,
			'OSSAccessKeyId': this.accessid,
			'success_action_status': '200', //让服务端返回200,不然，默认会返回204
			'signature': this.signature,
			'x-oss-security-token': this.stsToken,
		};
		return new_multipart_params;

	}
}
export default function (data) {
	return new oss_util(data);
}
